import { mapGetters } from 'vuex'
import { handleExcelResponse } from '@/util/util'
import { defaultOption, columnDefaultOption } from '@/const/crud/crud'
export default function(name) {
  const api = require('@/api/' + name)
  return {
    data() {
      let tableOption = require('@/const/crud/' + name).tableOption
      tableOption = Object.assign({}, defaultOption, tableOption)
      tableOption.column = columnDefaultOption(tableOption.column)
      return {
        searchForm: {},
        form: {},
        params: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption
      }
    },
    computed: {
      ...mapGetters(['permissions']),
      bindVal() {
        return {
          ref: 'crud',
          option: this.tableOption,
          data: this.tableData,
          tableLoading: this.tableLoading,
          page: this.page
        }
      },
      onEvent() {
        return {
          'on-load': this.getList,
          'row-save': this.rowSave,
          'row-update': this.rowUpdate,
          'row-del': this.rowDel,
          'refresh-change': this.refreshChange,
          'search-reset': this.searchChange,
          'search-change': this.searchChange
        }
      }
    },
    methods: {
      getList(page) {
        this.tableLoading = true
        return api.fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, this.params, this.searchForm)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
        })
      },
      searchChange(form, done) {
        for(let key of Object.keys(form)){
          if(this.validatenull(form[key])){
            delete form[key]
          }
        }
        let dateIndex = 1
        for(let column of this.tableOption.column){
          let value = form[column.prop]
          if(column.search && column.searchRange && value){
            form['dates'+dateIndex] = form[column.prop]
            dateIndex++
            delete form[column.prop]
          }
        }
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page).then(() => {
          if(done){
            done()
          }
        })
      },
      refreshChange() {
        this.getList(this.page);
      },
      rowEdit(row, index){
        this.$refs.crud.rowEdit(row, index)
      },
      rowUpdate: function(row, index, done, loading) {
        const callback = () => {
          api.putObj(row).then(data => {
            this.$message.success('修改成功')
            done()
            this.getList(this.page)
          }).catch(() => {
            loading()
          })
        }
        if(typeof(this.beforeRowUpdate) == "function"){
          this.beforeRowUpdate(row, index, callback, loading)
        }else{
          callback()
        }
      },
      rowSave: function(row, done, loading) {
        const callback = () => {
          api.addObj(row).then(data => {
            this.$message.success('添加成功')
            done()
            this.getList(this.page)
          }).catch(() => {
            loading()
          })
        }
        // upload组件在不上传文件时会把值赋为[],这里强制设置为null
        for(let column of this.tableOption.column){
          if(column.type === 'upload'){
            if(this.validatenull(row[column.prop])){
              row[column.prop] = null
            }
          }
        }
        if(typeof(this.beforeRowSave) == "function"){
          this.beforeRowSave(row, callback, loading)
        }else{
          callback()
        }
      },
      rowDel: function(row, index) {
        var _this = this
        this.$confirm(`是否确认删除序号为${row.$index+1}的记录`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return api.delObj(row.id)
        }).then(data => {
          _this.$message.success('删除成功')
          this.getList(this.page)
        })
      },
      handleBatchSubmit(){
        var tableSelect = this.$refs.crud.tableSelect
        if(tableSelect.length == 0){
          this.$message.info('请选择要提交的记录')
          return
        }
        var ids = tableSelect.map(row => row.id)
        api.submit(ids).then(response => {
          this.$message.success('提交成功')
          this.getList(this.page)
        })
      },
      handleExport(){
        var query = Object.assign({}, this.params, this.searchForm)
        let loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        })
        api.exportExcel(query).then(response => {
          handleExcelResponse(response, this.exportName)
          loading.close();
        }).catch(() => {
          loading.close();
        })
      },
      handlePrint(){
        this.$refs.crud.rowPrint()
      },
      approveBefore(callback){
        var tableSelect = this.$refs.crud.tableSelect
        if(tableSelect.length == 0){
          this.$message.info('请选择要审批的记录')
        }else{
          callback()
        }
      },
      handleApprove({result, approveSuggestions}, done, loading){
        var tableSelect = this.$refs.crud.tableSelect
        var ids = tableSelect.map(row => row.id)
        var params = {
          ids: ids,
          result: result,
          suggestions: approveSuggestions
        }
        api.approve(params).then(reponse => {
          done()
          this.$message.success('审批成功')
          this.getList(this.page)
        }).catch(error => {
          console.error(error)
          loading()
        })
      }
    }
  }
}
